import 'package:flutter/material.dart';

class CascadingDropdown extends StatefulWidget {
  // const CascadingDropdown({Key? key}) : super(key: key); // Added key parameter

  @override
  State<CascadingDropdown> createState() => _CascadingDropdownState();
}

class _CascadingDropdownState extends State<CascadingDropdown> {
  // 省份数据
  final Map<String, List<String>> _data = {
    '北京': ['东城区', '西城区', '朝阳区', '海淀区'],
    '上海': ['黄浦区', '徐汇区', '长宁区', '静安区'],
    '广东': ['广州市', '深圳市', '珠海市', '东莞市'],
  };

  String? _selectedProvince;
  String? _selectedCity;
  List<String> _cities = [];

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Scaffold(
          appBar: AppBar(title: Text('分类选项')),
          body: Padding(
            padding: const EdgeInsets.all(16.0),
            child: SizedBox(
              height: 100,
              child: Row(
                children: [
                  // 省份下拉
                  Expanded(
                    child: DropdownButtonFormField<String>(
                      value: _selectedProvince,
                      hint: Text('选择省份'),
                      items:
                          _data.keys.map((String province) {
                            return DropdownMenuItem<String>(
                              value: province,
                              child: Text(province),
                            );
                          }).toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          _selectedProvince = newValue;
                          _selectedCity = null;
                          _cities = _data[newValue] ?? [];
                        });
                      },
                    ),
                  ),
                  SizedBox(width: 32), // 水平间距
                  // 城市下拉
                  Expanded(
                    child: DropdownButtonFormField<String>(
                      value: _selectedCity,
                      hint: Text('选择城市'),
                      items:
                          _cities.map((String city) {
                            return DropdownMenuItem<String>(
                              value: city,
                              child: Text(city),
                            );
                          }).toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          _selectedCity = newValue;
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
